/**
 * JimBot - Java IM Bot
 * Copyright (C) 2013 JimBot project
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ru.jimbot.protocol;

import java.io.IOException;
import java.util.Random;
import ru.jimbot.modules.AbstractProps;
import ru.jimbot.modules.MsgOutQueue;
import ru.jimbot.util.Log;
import ru.mmp.core.MMPClient;
import ru.mmp.core.Status;
import ru.mmp.listener.MessageListener;
import ru.mmp.listener.StatusListener;

/**
 * Класс, работающий с протоколом MMP (Mail.Ru Agent)
 * @author alex_xpert
 */
public class MMPProtocol extends AbstractProtocol implements StatusListener, MessageListener {
    public AbstractProps  psp;
    private MMPClient client;

    public MMPProtocol(AbstractProps props){
        psp = props;
        mq = new MsgOutQueue(this, props.getIntProperty("bot.pauseOut"),
                props.getIntProperty("bot.pauseRestart"),
                props.getIntProperty("bot.msgOutLimit"));
    }

    @Override
    public void connect() {
        mq.start();
        client = new MMPClient();
        client.addMessageListener(this);
        client.addStatusListener(this);
        client.setEmail(screenName);
        client.setPass(password);
        try {
            client.connect();
            Log.info("MRA Account " + baseUin + " Online"); 
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void reConnect() {
         disconnect();
         connect();
    }

    @Override
    public void disconnect() {
        try {
            mq.stop();
            client.removeMessageListener(this);
            client.removeStatusListener(this);
            client.disconnect();
            Log.info("MRA Account " + baseUin + " Offline"); 
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void setStatus(int status) {
        int stts_nmbr = status;
        if(stts_nmbr > 29) stts_nmbr = new Random().nextInt(29);
        client.setStatus(stts_nmbr, psp.getStringProperty("icq.STATUS_MESSAGE2").trim(), psp.getStringProperty("icq.STATUS_MESSAGE1").trim());
    }

    @Override
    public void sendMsg(String sn, String msg) {
        client.sendMsg(sn, msg);
    }

    @Override
    public void getMsg(String sendSN, String recivSN, String msg, boolean isOffline) {
        protList.getMsg(sendSN, recivSN, msg, isOffline);
    }

    @Override
    public void getStatus(String sn, int status) {
        protList.getStatus(sn, status);
    }

    @Override
    public void addContactList(String sn) {}

    @Override
    public void RemoveContactList(String sn) {}

    @Override
    public AbstractProps getProps() {
        return psp;
    }

    @Override
    public boolean userInfoRequest(String paramString1, String paramString2) {
        return true;
    }

    @Override
    public void authRequest(String paramString1, String paramString2) {}

    @Override
    public int getOuteqSize() {
         return this.mq.size();
    }

    @Override
    public void onLogin() {
        connected = true;
        client.setStatus(Status.STATUS_ONLINE, psp.getStringProperty("icq.STATUS_MESSAGE1"), psp.getStringProperty("icq.STATUS_MESSAGE2"));
    }
            
    @Override
    public void onLogout() {
        Log.error("Разрыв соединения: " + baseUin);
        try {
            Log.info("Переподключение через 1 минуту...");
            Thread.sleep(60000);
            this.reConnect();
        } catch (Exception ex) {
            connected = false;
        }
    }
    
    public boolean isOnLine() {
        return client == null ? false : connected;
    }
    
    /**
     * Запрашивать авторизацию?
     */
    public boolean isNoAuthUin(String uin){
        return psp.getBooleanProperty("chat.isAuthRequest");
    }

    @Override
    public void onAuthorizationError(String string) {}

    @Override
    public void onIncomingMessage(String string, String string1) {
        protList.getMsg(string, screenName, string1, false);
    }

    @Override
    public void onMessageAck() {}

    @Override
    public void onAuthorization(String string, String string1) {
        client.Authorize(string);
    }

    @Override
    public void onMessageError() {}
}
